from odoo import fields, models, api
from odoo.exceptions import UserError


class RPShipperAging(models.Model):
    _name = 'rp.aging'
    _description = '时效'
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '名称必须唯一')]

    def _default_get_hours(self):
        hours = self.env['uom.uom'].search([('name', '=', 'Hours')])
        return hours.id if hours else False

    name = fields.Char(string='名称', index=True, compute='_compute_name')

    type = fields.Selection(string='类型', selection=[('courier', '承运商'),
                                                      ('shipper', '托运商'),
                                                      ('both', '通用'),
                                                      ('neither', '都不')], default='both', required=True)
    time = fields.Integer(string='时间', default=0, required=True)

    time_uom_id = fields.Many2one(string='时间单位', comodel_name='uom.uom', domain=[('category_id', '=', 3)], default=_default_get_hours)
    standard_unit_time = fields.Float(string='标准单位时间', help='折算标准单位，用于排序', compute='_compute_name', store=True)

    desc = fields.Char(string='描述')
    active = fields.Boolean(string='有效', default=True)

    """
    Constrains
    """

    @api.constrains('standard_unit_time')
    def _constrains_standard_unit_time(self):
        rp_aging_list = self.env['rp.aging'].search([('id', '!=', self.id)]).mapped(lambda r: r.standard_unit_time)
        if self.standard_unit_time in rp_aging_list:
            raise UserError('您已经添加了相同标准时间的记录！请检查后重试！')

    """
    Depends
    """

    @api.depends('time', 'time_uom_id')
    def _compute_name(self):
        for rec in self:
            rec.name = False
            rec.standard_unit_time = False
            if rec.time and rec.time_uom_id:
                rec.name = str(rec.time) + rec.time_uom_id.name
                rec.standard_unit_time = round(rec.time * rec.time_uom_id.factor, 2)
